package com.newlink.building.secret.utils

import android.util.Base64
import com.google.android.gms.common.util.Hex
import java.lang.Exception
import java.security.Key
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

/**
 * Created by xiaodong on 2024/1/15.
 */
object Module_Secret_CryptoHandler {
    fun encrypt(keyBytes: ByteArray?, data: ByteArray?): ByteArray? {
        try {
            val secretKey: Key = SecretKeySpec(keyBytes, "AES")
            val cipher: Cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
            cipher.init(Cipher.ENCRYPT_MODE, secretKey)
            return cipher.doFinal(data)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun encryptBase64String(key: String, plaintext: String): String? {
        try {
            val encryptedBytes =
                encrypt(Hex.stringToBytes(key), plaintext.toByteArray(charset("UTF-8")))
            return Base64.encodeToString(encryptedBytes, Base64.DEFAULT)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }
}